#include "host.h"
#include "arith_pid.h"
#include "thread_manager.h"
#include <math.h>

static void work_mode_off(void);
static void work_mode_normal(void);
void host_mode(void)
{
    struct Msg_InterThread msg[2];

    if(host_data->tecCtrlMode == TEC_Ctrl_Mode_Auto)
    {
        switch(host_data->workMode)
        {
            case Work_Mode_Off:
                work_mode_off();
                break;
            case Work_Mode_Normal:
                work_mode_normal();
                break;
        } 
    }
    msg[0].arg_id = ARG_ID_PV;
    msg[0].arg_value = temp_avg / 100;
    msg[1].arg_id = ARG_ID_TECPower;
    msg[1].arg_value = host_data->tecPower;
    rt_mq_send(mq_comm, &msg, sizeof(msg));
}

static void work_mode_off(void)
{
    host_data->tecPower = 0;
    can_send_data(0xFF, CAN_Data_TEC_Power, (rt_uint8_t *)&host_data->tecPower, sizeof(host_data->tecPower));
}
static void work_mode_normal(void)
{
    rt_int32_t sv, pv;
    rt_int16_t tecPower;
    rt_uint16_t pidConfig[3];
    struct Msg_InterThread msg[4];

    sv = host_data->sv * pow(10, 2 + Decimal_Point_Nbr_2 - host_data->decimalPointNbr);
    pv = temp_avg;
    rt_memcpy(pidConfig, &host_data->pidKp, sizeof(pidConfig));
    if(host_data->atEnable != 0)
    {
        if(pid_at(pidConfig, sv, pv, &tecPower) == 1)
        {
            host_data_set_atEnable(0);
            host_data_set_pidKp(pidConfig[0]);
            host_data_set_pidKi(pidConfig[1]);
            host_data_set_pidKd(pidConfig[2]);

            msg[0].arg_id = ARG_ID_AT;
            msg[0].arg_value = host_data->atEnable;
            msg[1].arg_id = ARG_ID_PIDKp;
            msg[1].arg_value = host_data->pidKp;
            msg[2].arg_id = ARG_ID_PIDKi;
            msg[2].arg_value = host_data->pidKi;
            msg[3].arg_id = ARG_ID_PIDKd;
            msg[3].arg_value = host_data->pidKd;
            rt_mq_send(mq_comm, &msg, sizeof(msg));
        }
        host_data->tecPower = tecPower;
        can_send_data(0xFF, CAN_Data_TEC_Power, (rt_uint8_t *)&host_data->tecPower, sizeof(host_data->tecPower));
    }
    else
    {
        pid_normal(pidConfig, sv, pv, &tecPower);
        host_data->tecPower = tecPower;
		/* 若使用单独补偿,清注释掉此处 */	
        can_send_data(0xFF, CAN_Data_TEC_Power, (rt_uint8_t *)&host_data->tecPower, sizeof(host_data->tecPower));

        /* 在此处对各通道进行单独补偿 */
        // for(rt_uint8_t i = 0; i < 16; i++)
        // {
        //     if(slaver_online_status & (1 << i))
        //     {

        //         can_send_data(i, CAN_Data_TEC_Power, (rt_uint8_t *)&host_data->tecPower, sizeof(host_data->tecPower));
        //     }
        // }
    }
}